import React, { useState, useEffect } from 'react';
import Modal from '../components/Modal';

interface EditPanelProps {
  activeNote: Note | null;
  onNoteEdit: (title: string, body: string) => void;
}

const EditPanel: React.FC<EditPanelProps> = ({ activeNote, onNoteEdit }) => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [tempTitle, setTempTitle] = useState('');
  const [tempBody, setTempBody] = useState('');

  useEffect(() => {
    if (activeNote) {
      setTitle(activeNote.title);
      setBody(activeNote.body);
    }
  }, [activeNote]);

  const handleBlur = () => {
    setTempTitle(title);
    setTempBody(body);
    setIsModalOpen(true);
  };

  const handleConfirm = () => {
    if (activeNote) {
      onNoteEdit(tempTitle, tempBody);
    }
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setTitle(activeNote ? activeNote.title : '');
    setBody(activeNote ? activeNote.body : '');
    setIsModalOpen(false);
  };

  return (
    <div className="notes__preview">
      <div className="notes__preview_container" >
        <input
          className="notes__title"
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          onBlur={handleBlur}
          placeholder="新笔记..."
        />
      </div>
      <textarea
        className="notes__body"
        value={body}
        onChange={(e) => setBody(e.target.value)}
        onBlur={handleBlur}
        placeholder="编辑笔记..."
      />
      <Modal 
        isOpen={isModalOpen}
        onRequestClose={handleCancel}
        onConfirm={handleConfirm}
        content="确认要保存更改吗？"
      />
    </div>
  );
};

export default EditPanel;

interface Note {
  id: number;
  title: string;
  body: string;
  updated: string;
}
